package cn.com.goldhs.architecture.inter.impl;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.ReturnableEvaluator;
import org.neo4j.graphdb.StopEvaluator;
import org.neo4j.graphdb.Traverser;
import org.neo4j.graphdb.Traverser.Order;
import org.neo4j.helpers.collection.IterableWrapper;

import cn.com.goldhs.architecture.RelationShipTypes;
import cn.com.goldhs.architecture.inter.Base;
import cn.com.goldhs.architecture.inter.Leader;

public class LeaderImpl extends BaseImpl implements
		Leader {

	public LeaderImpl(Node node) {
		super(node);
	}

	public LeaderImpl(Node node, String name) {
		super(node, name);
	}

	@Override
	public void addSubLeader(Leader leader) {
		this.getUnderlyingContainer().createRelationshipTo(((LeaderImpl)leader).getUnderlyingContainer(), RelationShipTypes.SubLeader);
	}

	@Override
	public Iterable<Leader> listSubLeaders() {
		Traverser traverser = this.getUnderlyingContainer().traverse(
				Order.BREADTH_FIRST, StopEvaluator.DEPTH_ONE,
				ReturnableEvaluator.ALL_BUT_START_NODE,
				RelationShipTypes.SubLeader, Direction.OUTGOING);

		return new IterableWrapper<Leader, Node>(traverser) {
			@Override
			protected Leader underlyingObjectToObject(Node node) {
				return new LeaderImpl(node);
			}
		};
	}
	
	@Override
	public Base getParent() {
		if(this.getUnderlyingContainer().hasRelationship(Direction.INCOMING, RelationShipTypes.SubLeader)) {
			Relationship rel = this.getUnderlyingContainer().getRelationships(Direction.INCOMING, RelationShipTypes.SubLeader).iterator().next();
			if(rel != null) {
				return new BaseImpl(rel.getStartNode());
			}
		}
		return null;
	}
}
